package com.my.project.dubbo.order.provider;

import com.my.project.dubbo.order.api.IOrderService;
import com.my.project.dubbo.order.dal.OrderDao;
import com.my.project.dubbo.order.dto.OrderRequestDto;
import com.my.project.dubbo.order.dto.OrderResponseDto;
import com.my.project.dubbo.user.api.UserService;
import com.my.project.dubbo.user.dto.DebitRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.jta.JtaTransactionManager;

import javax.transaction.SystemException;
import javax.transaction.UserTransaction;

/**
 * @Author:wangbin.
 * @Description.
 * @Date:Created in 10:14 2017/8/17.
 * @Modified By:
 */
@Service("orderService")
public class IOrderServiceImpl implements IOrderService {

    @Autowired
    JtaTransactionManager jtaTransactionManager;

    @Autowired
    OrderDao orderDao;

    @Autowired
    UserService userService;

    @Transactional(rollbackFor = RuntimeException.class)
    public OrderResponseDto addOrder(OrderRequestDto request) {
        System.out.println("request 曾经来过：" + request.toString());

        OrderResponseDto responseDto = new OrderResponseDto();
        responseDto.setCode("000000");
        responseDto.setMessage("添加订单成功");

        // 模拟下单后要同时扣减用户余额，用户模块和订单模块分别部署在不同的机器，所使用不同数据库
        // 模拟操作分布式事务
        orderDao.insertOrder();
        userService.debit(new DebitRequest());

        return responseDto;
        /*
        // 非注解方式处理
        UserTransaction userTransaction = jtaTransactionManager.getUserTransaction();
        try {
            userTransaction.begin();
            orderDao.insertOrder();
            userService.debit(new DebitRequest());
            userTransaction.commit();
        } catch (NotSupportedException e) {
            transactionErrorProcess(userTransaction);
        } catch (SystemException e) {
            transactionErrorProcess(userTransaction);
        } catch (RollbackException e) {
            transactionErrorProcess(userTransaction);
        } catch (HeuristicMixedException e) {
            transactionErrorProcess(userTransaction);
        } catch (HeuristicRollbackException e) {
            transactionErrorProcess(userTransaction);
        } catch (Exception e) {
            transactionErrorProcess(userTransaction);
        }*/
    }

    /**
     * 分布式事务回滚
     * @param userTransaction
     */
    private void transactionErrorProcess(UserTransaction userTransaction)
    {
        try {
            userTransaction.rollback();
        } catch (SystemException e1) {
            e1.printStackTrace();
        }
    }

    public OrderResponseDto deleteOrder(String id) {
        System.out.println("删除订单：" + id);

        OrderResponseDto responseDto = new OrderResponseDto();
        responseDto.setCode("1000");
        responseDto.setMessage("删除订单成功");
        return responseDto;
    }
}
